/*
 * UpdateResources.java
 *
 * Created on May 5, 2009, 6:21 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package im.resources;

import im.messages.ResourceMessage;
import im.resources.monitors.CPUMonitor;
import im.node.MobileNodeAgent;
import im.resources.ResourceStatus;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.ControllerException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author bluejack
 */
public class UpdateResources extends CyclicBehaviour {
    MobileNodeAgent mobileNodeAgent = null;

    boolean statusChanged = false;
    
    CPUMonitor cpu = new CPUMonitor();

    public UpdateResources(MobileNodeAgent mobileNodeAgent) {
        this.mobileNodeAgent = mobileNodeAgent;
    }
    public void action() {
        updateStatus();
        if(statusChanged())
            sendStatus(mobileNodeAgent.getClusterHeadID());
    }

    public boolean checkStatus() {
        return true;
    }

    private void sendStatus(String clusterHeadID) {
        AID ch = new AID();
        ch.setName(clusterHeadID);

        ACLMessage msg = new ACLMessage(ACLMessage.UNKNOWN);
        msg.setEncoding(im.general.Config.UPDATE_STATUS_NAME);
        msg.addReceiver(ch);
        ResourceMessage resourceMessage = null;
        try {
            mobileNodeAgent.updateResources();
            resourceMessage = new ResourceMessage(mobileNodeAgent.getStatus(), mobileNodeAgent.getContainerController().getContainerName());
        } catch (ControllerException ex) {
            Logger.getLogger(UpdateResources.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            msg.setContentObject(resourceMessage);
        } catch (IOException ex) {
            Logger.getLogger(UpdateResources.class.getName()).log(Level.SEVERE, null, ex);
        }
        mobileNodeAgent.sendMessage(msg);
    }

    private boolean statusChanged() {
        return statusChanged;
    }

    private void updateStatus() {
        //TODO ma questa a che serve? la usa qualcuno?
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
